package binfa;

public class jiaotidaying {
    static jiaotidaying test3 = new jiaotidaying();
    boolean flag = true;
    static  int n=0;
     static int m=1;
    public static void main(String[] args)  {
       new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    test3.method1();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    test3.mothod2();
                }
            }
        }).start();
    }

    public synchronized void method1(){
        try {
            if (!flag){
                this.wait();
            }

            flag = false;//将flag置为false，是为了方便线程2被唤醒后开始工作，不然线程2还会被wait()
            System.out.println(n);
            n=n+2;
            Thread.sleep(1000);
            this.notify();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void mothod2(){
        try {
            if(flag){
                this.wait();
            }

            flag = true;//将flag置为true，是为了方便线程1被唤醒后开始工作，不然线程1还会被wait()
            System.out.println(m);
            m=m+2;
            Thread.sleep(1000);
            this.notify();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}